package com.kyg.tjtoolmanager.controller;

import com.alibaba.fastjson.JSONArray;
import com.kyg.tjtoolmanager.App;
import com.kyg.tjtoolmanager.db.SQLiteUtils;
import com.kyg.tjtoolmanager.driver.UDevice;
import com.kyg.tjtoolmanager.driver.UHFRFIDDriver;
import com.kyg.tjtoolmanager.module.Goods;
import com.kyg.tjtoolmanager.module.Reader;
import com.kyg.tjtoolmanager.net.http.HttpBack;
import com.kyg.tjtoolmanager.net.http.HttpEntity;
import com.kyg.tjtoolmanager.net.http.HttpService;
import com.kyg.tjtoolmanager.net.http.HttpURL;
import com.kyg.tjtoolmanager.ui.ProgressStage;
import com.kyg.tjtoolmanager.ui.StageUIHelper;
import com.sun.jna.Pointer;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import okhttp3.Call;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GetGoodsController extends BaseController {

    @FXML
    VBox vboxReader;
    List<Reader> readerList = new ArrayList<>();
    public List<String> lastTags = new ArrayList<>(); //上次读到的标签
    public List<String> currentTags = new ArrayList<>(); //当前读到的标签
    private int MAX_READER_TIMES = 4;
    private int zeroTimes = MAX_READER_TIMES;
    private List<UDevice> listUDevice = new ArrayList<>();

    interface GoodsDataCallback {
        void onSuccess(List<Goods> goodsList);
    }

    @Override
    public void onShow() {
        super.onShow();
        startWorkerReader();
    }

    /**
     * 启动工作台读写器
     * 1.各读写器判断启动状态
     * 2.根据读写器标签获取数据
     */
    public void startWorkerReader() {
        currentTags.clear();
        zeroTimes = MAX_READER_TIMES;
        readerList = SQLiteUtils.getReaderByType("1");
        refreshReaderUI();
        for (int i = 0; i < readerList.size(); i++) {
            Reader reader = readerList.get(i);
            SQLiteUtils.insertLog(reader.toString());
            doInventory(reader);
        }
    }

    public void stopWorkerReader() {
        for (int i = 0; i < listUDevice.size(); i++) {
            UHFRFIDDriver.rfidDriver.UHF_RFID_StopInventory(listUDevice.get(i));
        }
    }

    private synchronized void refreshReaderUI() {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                if (readerList == null || readerList.size() == 0) {
                    Label label = new Label("未设置工作台读写器！");
                    vboxReader.getChildren().add(label);
                    return;
                }
                vboxReader.getChildren().clear();
                for (int i = 0; i < readerList.size(); i++) {
                    Reader reader = readerList.get(i);
                    Label label = new Label();
                    StringBuilder stats = new StringBuilder();
                    stats.append((i + 1) + ". ");
                    if (reader.conType == 1) {
                        stats.append(reader.serial + " " + reader.baud);
                    } else {
                        stats.append(reader.ip + ":" + reader.ipPort);
                    }
                    if (reader.conStatus == -1) {
                        stats.append(" 正在连接");
                    } else if (reader.conStatus == 0) {
                        stats.append(" 连接失败，开始重连");
                        doInventory(reader);
                    } else if (reader.conStatus == 1) {
                        stats.append(" 连接成功");
                    }
                    label.setAlignment(Pos.CENTER_LEFT);
                    label.setText(stats.toString());
                    vboxReader.getChildren().add(label);
                }
            }
        });
    }

    private void doInventory(Reader reader) {
        reader.conStatus = -1;
        new Thread(new Runnable() {
            @Override
            public void run() {
                UDevice uDevice = null;
                if (reader.conType == 1) {
                    uDevice = UHFRFIDDriver.rfidDriver.UHF_RFID_Init(reader.serial, reader.baud);
                } else {
                    uDevice = UHFRFIDDriver.rfidDriver.UHF_RFID_NetInit(reader.ip, reader.ipPort);
                }
                if (uDevice == null) {
                    reader.conStatus = 0;
                    SQLiteUtils.insertLog("连接失败");
                } else {
                    reader.conStatus = 1;
                    SQLiteUtils.insertLog("连接成功：" + uDevice.toString());
                    listUDevice.add(uDevice);
                    int Status = 1;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    UHFRFIDDriver.rfidDriver.UHF_RFID_Reg_InvTagCallBack(uDevice, new UHFRFIDDriver.InventoryTagCallback() {

                        @Override
                        public void onTagCallback(Pointer data, int length) {
                            try {
                                //数据格式： 前两位=数据长度，倒数第三第二位=信号强度，最后一位=天线号，中间数据=EPC
                                byte[] result = data.getByteArray(0, length);
                                StringBuilder tagData = new StringBuilder();
                                for (int i = 0; i < length; i++) {
                                    tagData.append(String.format("%02X", result[i]));
                                }
                                addTagToList(tagData.toString());
//                        updateText("返回数据长度："+result.length+"  length："+length);
//                        updateText("onTagCallback data:" + data.getPointer(0).getByteArray(0,length)+ "  length:" + length);
                            } catch (Exception ex) {
                                SQLiteUtils.insertLog(ex.getMessage());
                            }
                        }
                    });

                    //开始连续寻标签
                    Status = UHFRFIDDriver.rfidDriver.UHF_RFID_IventoryContinuity(uDevice, (short) 0);
                    if (Status < 0) {
                        SQLiteUtils.insertLog("UHF_RFID_IventoryContinuity fail");
                    } else {
                        SQLiteUtils.insertLog("UHF_RFID_IventoryContinuity success");
                    }
                }
                refreshReaderUI();
            }
        }).start();
    }

    private synchronized void addTagToList(String tag) {
        String text = tag.substring(4);
        tag = text.substring(0, text.length() - 6);
        if (!currentTags.contains(tag)) {
            currentTags.add(tag);
            SQLiteUtils.insertLog("读到标签：" + tag);
        } else {
            zeroTimes--;
            if (zeroTimes <= 0) {
                stopWorkerReader();
                //扫码完毕
                getTagInfo();
            }
        }
    }

    private void getTagInfo() {
        //判断本次获取标签与上次是否一致
        boolean equal = true;
        if (currentTags.size() == lastTags.size()) {
            for (int i = 0; i < lastTags.size(); i++) {
                if (!currentTags.contains(lastTags.get(i))) {
                    equal = false;
                    break;
                }
            }
        } else {
            equal = false;
        }
        if (equal) {
            //标签相同，重新读取
            SQLiteUtils.insertLog("标签无变化，重新读取标签");
            startWorkerReader();
            return;
        }
        StringBuffer sAll = new StringBuffer();
        for (int a = 0; a < lastTags.size(); a++) {
            sAll.append(lastTags.get(a));
            sAll.append(",");
        }
        if (sAll.length() > 0) {
            sAll = sAll.deleteCharAt(sAll.length() - 1);
        }
        SQLiteUtils.insertLog("标签号：" + sAll.toString());
        getGoodByScanCode(sAll.toString(), true);
    }

    //根据标签号(编码)获取物品信息
    public synchronized void getGoodByScanCode(String code, boolean isReader) {
        ProgressStage progressStage = ProgressStage.of((Stage) rootLayout.getScene().getWindow(), "正在查询");
        progressStage.show();

        Map<String, String> postParams = new HashMap<>();
        postParams.put("code_num", code);
        HttpService.getInstance().httpPostMap(HttpURL.URL(HttpURL.GET_GOODS_BY_CODE), postParams, new HttpBack() {
            @Override
            public void onSuccess(Call call, HttpEntity httpEntity) {
                progressStage.close();
                SQLiteUtils.insertLog("查询接口返回：" + httpEntity.toString());
                if (httpEntity.getCode() == 1) {
                    List<Goods> goodsList = JSONArray.parseArray(httpEntity.getData().toString(), Goods.class);
                    insertToBorrowList(goodsList, isReader);
                    if (isReader) {
                        lastTags.clear();
                        lastTags.addAll(currentTags);
                        startWorkerReader();
                    }
                } else {
                    StageUIHelper.getInstance().showTipAlert(httpEntity.getMsg());
                }
            }

            @Override
            public void onFail(Call call, String e) {
                progressStage.close();
                SQLiteUtils.insertLog("查询接口错误：" + e);
                StageUIHelper.getInstance().showTipAlert(e);
            }
        });
    }

    public void getGoodsByName(String name, GoodsDataCallback callback) {
        ProgressStage progressStage = ProgressStage.of((Stage) rootLayout.getScene().getWindow(), "正在查询");
        progressStage.show();

        Map<String, String> postParams = new HashMap<>();
        postParams.put("keyword", name);
        postParams.put("status", "1"); //等于空 代表获取所有数据 -1获取待绑定数据 0领用 1获取在库数据 2获取维修数据 3获取报废数据4出库5待入库
        postParams.put("page", "1");
        postParams.put("currnum", "100");
        HttpService.getInstance().httpPostMap(HttpURL.URL(HttpURL.GET_GOODS_INFO), postParams, new HttpBack() {
            @Override
            public void onSuccess(Call call, HttpEntity httpEntity) {
                progressStage.close();
                SQLiteUtils.insertLog("查询接口返回：" + httpEntity.toString());
                if (httpEntity.getCode() == 1) {
                    List<Goods> goodsList = JSONArray.parseArray(httpEntity.getData().toString(), Goods.class);
                    if (callback != null) {
                        callback.onSuccess(goodsList);
                    }
                } else {
                    StageUIHelper.getInstance().showTipAlert(httpEntity.getMsg());
                }
            }

            @Override
            public void onFail(Call call, String e) {
                progressStage.close();
                SQLiteUtils.insertLog("查询接口错误：" + e);
                StageUIHelper.getInstance().showTipAlert(e);
            }
        });
    }

    public void insertToBorrowList(List<Goods> goodsList, boolean isReader) {

    }

}
